<?php
$page_title = '安排教室监考员 - 考务管理系统';

// 开启会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

// 数据库连接
try {
    require_once 'database.php';
    $db_connected = isset($conn) && $conn instanceof mysqli;
} catch (Exception $e) {
    error_log("数据库连接失败: " . $e->getMessage());
    $db_connected = false;
}

if (!$db_connected) {
    $_SESSION['error_message'] = "数据库连接失败，请联系管理员";
    header('Location: user_home.php');
    exit();
}

// 获取考试项目列表
$exams_sql = "SELECT id, exam_name, exam_date, start_time, end_time FROM exam_projects WHERE status = 'active' ORDER BY exam_date ASC";
$exams_result = $conn->query($exams_sql);

// 获取教室列表
$rooms_sql = "SELECT id, room_name, capacity, location FROM rooms WHERE status = 'available' ORDER BY room_name ASC";
$rooms_result = $conn->query($rooms_sql);

// 获取监考员列表（在职员工）
$invigilators_sql = "SELECT user_id, name, position, dept_id FROM staff WHERE serving = TRUE ORDER BY name ASC";
$invigilators_result = $conn->query($invigilators_sql);

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $exam_id = intval($_POST['exam_id']);
    $room_id = intval($_POST['room_id']);
    $invigilator_ids = isset($_POST['invigilator_ids']) ? $_POST['invigilator_ids'] : [];

    // 验证输入
    if ($exam_id <= 0 || $room_id <= 0) {
        $error_message = "请选择有效的考试项目和教室";
    } elseif (empty($invigilator_ids)) {
        $error_message = "请至少选择一名监考员";
    } else {
        // 检查是否已存在安排
        $check_sql = "SELECT id FROM exam_arrangements WHERE exam_id = ? AND room_id = ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param("ii", $exam_id, $room_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();

        if ($check_result->num_rows > 0) {
            $error_message = "该考试项目和教室的安排已存在";
        } else {
            $conn->begin_transaction();
            try {
                // 插入考试安排
                $insert_arrangement_sql = "INSERT INTO exam_arrangements (exam_id, room_id, created_by, created_at) VALUES (?, ?, ?, NOW())";
                $insert_arrangement_stmt = $conn->prepare($insert_arrangement_sql);
                $insert_arrangement_stmt->bind_param("iii", $exam_id, $room_id, $_SESSION['user_id']);
                $insert_arrangement_stmt->execute();

                $arrangement_id = $conn->insert_id;

                // 插入监考员安排
                $insert_invigilator_sql = "INSERT INTO invigilator_assignments (arrangement_id, invigilator_id, created_at) VALUES (?, ?, NOW())";
                $insert_invigilator_stmt = $conn->prepare($insert_invigilator_sql);

                foreach ($invigilator_ids as $invigilator_id) {
                    $insert_invigilator_stmt->bind_param("ii", $arrangement_id, $invigilator_id);
                    $insert_invigilator_stmt->execute();
                }

                $conn->commit();
                $success_message = "教室监考员安排成功！";

                // 清空表单
                $exam_id = $room_id = 0;
                $invigilator_ids = [];

            } catch (Exception $e) {
                $conn->rollback();
                $error_message = "安排失败：" . $e->getMessage();
            }
        }
    }
}

// 获取已有安排
$arrangements_sql = "SELECT ea.id, ep.exam_name, ep.exam_date, ep.start_time, ep.end_time,
                            r.room_name, r.capacity, r.location,
                            GROUP_CONCAT(s.name SEPARATOR ', ') as invigilators
                     FROM exam_arrangements ea
                     JOIN exam_projects ep ON ea.exam_id = ep.id
                     JOIN rooms r ON ea.room_id = r.id
                     LEFT JOIN invigilator_assignments ia ON ea.id = ia.arrangement_id
                     LEFT JOIN staff s ON ia.invigilator_id = s.user_id
                     GROUP BY ea.id
                     ORDER BY ep.exam_date ASC, ep.start_time ASC";
$arrangements_result = $conn->query($arrangements_sql);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- 统一样式 -->
    <link rel="stylesheet" href="css/unified-style.css">
</head>
<body>
    <!-- 导航栏 -->
    <?php include_once 'common/navigation.php'; ?>

    <!-- 主要内容 -->
    <div class="container main-content">
        <!-- 页面标题 -->
        <div class="card">
            <div class="page-header">
                <h1 class="page-title">安排教室监考员</h1>
                <p class="page-subtitle">为考试项目分配教室和监考员</p>
            </div>
        </div>

        <!-- 消息提示 -->
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success fade-in">
                <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
            </div>
        <?php elseif (isset($error_message)): ?>
            <div class="alert alert-danger fade-in">
                <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
            </div>
        <?php endif; ?>

        <!-- 安排表单 -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-plus-circle"></i> 新建安排
            </div>
            <div class="card-body">
                <form method="post" class="needs-validation" novalidate>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="exam_id" class="form-label">
                                    <i class="fas fa-file-alt"></i> 考试项目 <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="exam_id" name="exam_id" required>
                                    <option value="">请选择考试项目</option>
                                    <?php if ($exams_result && $exams_result->num_rows > 0): ?>
                                        <?php while($exam = $exams_result->fetch_assoc()): ?>
                                            <option value="<?php echo $exam['id']; ?>"
                                                    <?php echo (isset($exam_id) && $exam_id == $exam['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($exam['exam_name']); ?>
                                                (<?php echo $exam['exam_date']; ?> <?php echo $exam['start_time']; ?>-<?php echo $exam['end_time']; ?>)
                                            </option>
                                        <?php endwhile; ?>
                                    <?php endif; ?>
                                </select>
                                <div class="invalid-feedback">
                                    请选择考试项目
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="room_id" class="form-label">
                                    <i class="fas fa-door-open"></i> 考试教室 <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="room_id" name="room_id" required>
                                    <option value="">请选择教室</option>
                                    <?php if ($rooms_result && $rooms_result->num_rows > 0): ?>
                                        <?php while($room = $rooms_result->fetch_assoc()): ?>
                                            <option value="<?php echo $room['id']; ?>"
                                                    <?php echo (isset($room_id) && $room_id == $room['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($room['room_name']); ?>
                                                (容量: <?php echo $room['capacity']; ?>人, <?php echo htmlspecialchars($room['location']); ?>)
                                            </option>
                                        <?php endwhile; ?>
                                    <?php endif; ?>
                                </select>
                                <div class="invalid-feedback">
                                    请选择教室
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">
                            <i class="fas fa-user-tie"></i> 监考员 <span class="text-danger">*</span>
                        </label>
                        <div class="row">
                            <?php if ($invigilators_result && $invigilators_result->num_rows > 0): ?>
                                <?php while($invigilator = $invigilators_result->fetch_assoc()): ?>
                                    <div class="col-md-4 col-sm-6">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox"
                                                   name="invigilator_ids[]"
                                                   value="<?php echo $invigilator['user_id']; ?>"
                                                   id="invigilator_<?php echo $invigilator['user_id']; ?>"
                                                   <?php echo (isset($invigilator_ids) && in_array($invigilator['user_id'], $invigilator_ids)) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="invigilator_<?php echo $invigilator['user_id']; ?>">
                                                <?php echo htmlspecialchars($invigilator['name']); ?>
                                                <small class="text-muted">(<?php echo htmlspecialchars($invigilator['position']); ?>)</small>
                                            </label>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="col-12">
                                    <div class="alert alert-warning">
                                        <i class="fas fa-exclamation-triangle"></i> 暂无可用的监考员
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="invalid-feedback">
                            请至少选择一名监考员
                        </div>
                    </div>

                    <div class="d-flex justify-content-between">
                        <a href="exam_management.php" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> 返回考试管理
                        </a>
                        <div>
                            <button type="reset" class="btn btn-outline-secondary me-2">
                                <i class="fas fa-undo"></i> 重置
                            </button>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存安排
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 已有安排列表 -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-list"></i> 已有安排
            </div>
            <div class="card-body">
                <?php if ($arrangements_result && $arrangements_result->num_rows > 0): ?>
                    <div class="table-container">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th><i class="fas fa-file-alt"></i> 考试项目</th>
                                    <th><i class="fas fa-calendar"></i> 考试时间</th>
                                    <th><i class="fas fa-door-open"></i> 教室</th>
                                    <th><i class="fas fa-user-tie"></i> 监考员</th>
                                    <th><i class="fas fa-cog"></i> 操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while($arrangement = $arrangements_result->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($arrangement['exam_name']); ?></strong>
                                        </td>
                                        <td>
                                            <small>
                                                <?php echo $arrangement['exam_date']; ?><br>
                                                <?php echo $arrangement['start_time']; ?> - <?php echo $arrangement['end_time']; ?>
                                            </small>
                                        </td>
                                        <td>
                                            <?php echo htmlspecialchars($arrangement['room_name']); ?>
                                            <small class="text-muted">
                                                <br>(<?php echo $arrangement['capacity']; ?>人, <?php echo htmlspecialchars($arrangement['location']); ?>)
                                            </small>
                                        </td>
                                        <td>
                                            <small><?php echo htmlspecialchars($arrangement['invigilators']); ?></small>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-danger"
                                                    onclick="deleteArrangement(<?php echo $arrangement['id']; ?>)">
                                                <i class="fas fa-trash"></i> 删除
                                            </button>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <div class="text-center py-5">
                        <div class="mb-3">
                            <i class="fas fa-calendar-times" style="font-size: 48px; color: #6c757d;"></i>
                        </div>
                        <h4 class="text-muted">暂无安排记录</h4>
                        <p class="text-muted">请创建第一个教室监考员安排</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- 安排说明 -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-info-circle"></i> 安排说明
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6><i class="fas fa-check text-success"></i> 安排要求</h6>
                        <ul class="list-unstyled">
                            <li><i class="fas fa-dot-circle text-primary"></i> 每个教室至少需要1名监考员</li>
                            <li><i class="fas fa-dot-circle text-primary"></i> 建议大教室配置2名以上监考员</li>
                            <li><i class="fas fa-dot-circle text-primary"></i> 同一考试项目可安排多个教室</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <h6><i class="fas fa-lightbulb text-warning"></i> 注意事项</h6>
                        <ul class="list-unstyled">
                            <li><i class="fas fa-dot-circle text-warning"></i> 确认监考员时间无冲突</li>
                            <li><i class="fas fa-dot-circle text-warning"></i> 教室容量要满足考试需求</li>
                            <li><i class="fas fa-dot-circle text-warning"></i> 安排后会自动通知相关人员</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
    // 表单验证
    (function() {
        'use strict';
        window.addEventListener('load', function() {
            var forms = document.getElementsByClassName('needs-validation');
            var validation = Array.prototype.filter.call(forms, function(form) {
                form.addEventListener('submit', function(event) {
                    // 检查是否选择了监考员
                    const checkedInvigilators = document.querySelectorAll('input[name="invigilator_ids[]"]:checked');
                    if (checkedInvigilators.length === 0) {
                        event.preventDefault();
                        event.stopPropagation();
                        alert('请至少选择一名监考员');
                        return false;
                    }

                    if (form.checkValidity() === false) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    form.classList.add('was-validated');
                }, false);
            });
        }, false);
    })();

    // 删除安排
    function deleteArrangement(arrangementId) {
        if (confirm('确定要删除这个安排吗？此操作不可撤销。')) {
            // 创建表单并提交
            const form = document.createElement('form');
            form.method = 'post';
            form.style.display = 'none';

            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'delete_arrangement';
            input.value = arrangementId;

            form.appendChild(input);
            document.body.appendChild(form);
            form.submit();
        }
    }

    // 自动隐藏成功消息
    setTimeout(function() {
        const successAlert = document.querySelector('.alert-success');
        if (successAlert) {
            successAlert.style.opacity = '0';
            setTimeout(() => successAlert.remove(), 300);
        }
    }, 3000);
    </script>

    <?php
    // 处理删除安排
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_arrangement'])) {
        $arrangement_id = intval($_POST['delete_arrangement']);

        $conn->begin_transaction();
        try {
            // 删除监考员分配
            $delete_invigilators_sql = "DELETE FROM invigilator_assignments WHERE arrangement_id = ?";
            $delete_invigilators_stmt = $conn->prepare($delete_invigilators_sql);
            $delete_invigilators_stmt->bind_param("i", $arrangement_id);
            $delete_invigilators_stmt->execute();

            // 删除安排
            $delete_arrangement_sql = "DELETE FROM exam_arrangements WHERE id = ?";
            $delete_arrangement_stmt = $conn->prepare($delete_arrangement_sql);
            $delete_arrangement_stmt->bind_param("i", $arrangement_id);
            $delete_arrangement_stmt->execute();

            $conn->commit();
            echo "<script>alert('安排删除成功！'); window.location.reload();</script>";
        } catch (Exception $e) {
            $conn->rollback();
            echo "<script>alert('删除失败：" . $e->getMessage() . "');</script>";
        }
    }

    // 关闭数据库连接
    if (isset($conn)) {
        $conn->close();
    }
    ?>
</body>
</html>